/**
 * 编译封装模板
 * @param source
 * @returns {string}
 */
function compile(source,mode){
    var component = VueTemplateCompiler.parseComponent(source);
    var script=component.script.content;
    var style=component.styles.map(function(it){return it.content}).join('\n');
    var template=component.template.content

    if(!script){
        script="return {}"
    }else{
        script = script.replace(/(\s|^)export\s+default\s*\{/, '\nreturn{')
        //替换import为require,
        script = script.replace(/import\s+([\{\w\,\}\s]+\s+from\s+)?(['"][\.\-\/\w]+['"])/g, function (res, v, f) {
            if (!v) {
                return 'require(' + f + ')'
            } else {
                var name = v.replace(/\s+from\s+$/, '');
                return 'const ' + name + ' = require(' + f + ')'
            }
        })
        script=jct.compScript(script)
    }
    var append=""
   // script+="\n~function(m){";
    if(template){
        var templateOut=VueTemplateCompiler.compile(template);
        //script+="m.render=function(){"+templateOut.render+"};"
        append+="render:function(){"+templateOut.render+"}"
        if(templateOut.staticRenderFns.length>0){
            append+=",staticRenderFns:["+templateOut.staticRenderFns.map(function(it){ return "function(){"+it+"}"}).join(",")+"]"
        }
    }
    if(style){
        style=jct.compStyle(style)
        if(append){
            append+=","
        }
        // var s="let idx=0;let sel=document.createElement(\"style\");sel.innerHTML='"+style.replace(/'/g,"\\'")+"';"
        // s+="var mixin={mounted(){idx++;if(idx==1){document.head.appendChild(sel)}},beforeDestroy() {idx--;if(idx<=0){document.head.removeChild(sel)}}};"
        // s+="m.mixins?m.mixins.push(mixin):m.mixins = [mixin];";
        // script+=s;
        append+="style:`"+style.replace(/\\/g,"\\\\").replace(/`/g,"\\`")+"`"
    }
    //script+="\n}(module.exports);"
    var a="_$(()=>{"+script+"})";
    if(mode==4){
        a=UglifyJS.minify(a).code
        a=a.substring(0,a.length-1);
    }
    return "define(((_)=>(require) =>_$("+a+", _))({"+append+"}))";
}
